package cn.yx.common.security.util;

import cn.yx.common.core.constant.NumberConstant;
import cn.yx.common.security.pojo.JwtUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>SpringSecurity用于获取用户信息的工具类</p>
 *
 * @author Wgssmart
 */
public final class SecurityUtil {

    private SecurityUtil() {
    }

    /**
     * 获取当前登录的JwtUserDetails，如果没有用户登录，则JwtUserDetails的id为0L
     *
     * @return
     */
    public static JwtUserDetails currentUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.nonNull(authentication)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof JwtUserDetails) {
                return (JwtUserDetails) principal;
            }
        }
        JwtUserDetails jwtUserDetails = new JwtUserDetails();
        jwtUserDetails.setId(NumberConstant.LONG_ZERO);
        return jwtUserDetails;
    }

    /**
     * 获取当前登录用户的id
     *
     * @return
     */
    public static Long currentUserId() {
        return currentUserDetails().getId();
    }

    /**
     * 获取当前登录用户的用户名（可能是账户名，手机号或邮箱账户）
     *
     * @return
     */
    public static String currentUsername() {
        return currentUserDetails().getUsername();
    }

    /**
     * 获取当前登录用户的所有角色
     *
     * @return
     */
    public static List<String> currentUserRoles() {
        Object authorities = currentUserDetails().getAuthorities();
        if (Objects.nonNull(authorities)) {
            Collection<SimpleGrantedAuthority> simpleGrantedAuthorityList = (Collection<SimpleGrantedAuthority>) authorities;
            List<String> roleList = new ArrayList<>();
            for (SimpleGrantedAuthority simpleGrantedAuthority : simpleGrantedAuthorityList) {
                roleList.add(simpleGrantedAuthority.getAuthority());
            }
            return roleList;
        }
        return new ArrayList<>();
    }

    /**
     * 使用BCrypt加密密码
     *
     * @param password
     * @return
     */
    public static String encryptPassword(String password) {
        return new BCryptPasswordEncoder().encode(password);
    }

    /**
     * 判断密码是否正确
     *
     * @param rawPassword     明文密码
     * @param encodedPassword 加密后的密码
     * @return
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return new BCryptPasswordEncoder().matches(rawPassword, encodedPassword);
    }

}
